const ChapterConfig = require('../models/ChapterConfig');
const { Op } = require('sequelize');

// 获取所有章节配置
const getAllChapterConfigs = async (req, res) => {
  try {
    const configs = await ChapterConfig.findAll({
      where: { isActive: true },
      order: [['chapterNumber', 'ASC']]
    });
    
    res.json({
      success: true,
      data: configs
    });
  } catch (error) {
    console.error('获取章节配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取章节配置失败',
      error: error.message
    });
  }
};

// 根据章节号获取配置
const getChapterConfigByNumber = async (req, res) => {
  try {
    const { chapterNumber } = req.params;
    
    const config = await ChapterConfig.findOne({
      where: { 
        chapterNumber: parseInt(chapterNumber),
        isActive: true 
      }
    });
    
    if (!config) {
      return res.status(404).json({
        success: false,
        message: '章节配置不存在'
      });
    }
    
    res.json({
      success: true,
      data: config
    });
  } catch (error) {
    console.error('获取章节配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取章节配置失败',
      error: error.message
    });
  }
};

// 获取章节号的最大值
const getMaxChapterNumber = async (req, res) => {
  try {
    const maxChapter = await ChapterConfig.max('chapterNumber', {
      where: { isActive: true }
    });
    
    // 如果没有任何章节配置，返回0，这样前端可以使用1作为第一个章节号
    const nextChapterNumber = (maxChapter || 0) + 1;
    
    res.json({
      success: true,
      data: {
        maxChapterNumber: maxChapter || 0,
        nextChapterNumber: nextChapterNumber
      }
    });
  } catch (error) {
    console.error('获取最大章节号失败:', error);
    res.status(500).json({
      success: false,
      message: '获取最大章节号失败',
      error: error.message
    });
  }
};

// 创建章节配置
const createChapterConfig = async (req, res) => {
  try {
    // 检查用户权限
    if (!req.user || !['admin', 'teacher'].includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员和教师可以创建章节配置'
      });
    }
    
    const {
      chapterNumber,
      chapterTitle,
      chapterDescription,
      docxConfig,
      pptxConfig,
      videosConfig,
      examplesConfig,
      practiceConfig,
      assignmentsConfig,
      weightConfig
    } = req.body;
    
    // 检查章节号是否已存在
    const existingConfig = await ChapterConfig.findOne({
      where: { chapterNumber }
    });
    
    if (existingConfig) {
      return res.status(400).json({
        success: false,
        message: '该章节配置已存在'
      });
    }
    
    const config = await ChapterConfig.create({
      chapterNumber,
      chapterTitle,
      chapterDescription,
      docxConfig,
      pptxConfig,
      videosConfig,
      examplesConfig,
      practiceConfig,
      assignmentsConfig,
      weightConfig,
      createdBy: req.user.id
    });
    
    res.status(201).json({
      success: true,
      message: '章节配置创建成功',
      data: config
    });
  } catch (error) {
    console.error('创建章节配置失败:', error);
    res.status(500).json({
      success: false,
      message: '创建章节配置失败',
      error: error.message
    });
  }
};

// 更新章节配置
const updateChapterConfig = async (req, res) => {
  try {
    // 检查用户权限
    if (!req.user || !['admin', 'teacher'].includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员和教师可以更新章节配置'
      });
    }
    
    const { id } = req.params;
    
    // 先获取现有配置
    const existingConfig = await ChapterConfig.findByPk(id);
    if (!existingConfig) {
      return res.status(404).json({
        success: false,
        message: '章节配置不存在'
      });
    }
    
    // 智能合并更新数据，只更新提交的字段
    const updateData = { updatedBy: req.user.id };
    
    // 基本字段更新
    if (req.body.chapterNumber !== undefined) updateData.chapterNumber = req.body.chapterNumber;
    if (req.body.chapterTitle !== undefined) updateData.chapterTitle = req.body.chapterTitle;
    if (req.body.chapterDescription !== undefined) updateData.chapterDescription = req.body.chapterDescription;
    if (req.body.isEnabled !== undefined) updateData.isEnabled = req.body.isEnabled;
    
    // 配置字段智能合并 - 只有明确提交的配置才会更新
    const configFields = ['docxConfig', 'pptxConfig', 'videosConfig', 'examplesConfig', 'practiceConfig', 'assignmentsConfig', 'weightConfig'];
    
    configFields.forEach(field => {
      if (req.body[field] !== undefined) {
        if (req.body[field] === null) {
          // 如果明确设置为null，则删除该配置
          updateData[field] = null;
        } else {
          // 如果提交了配置，则更新该配置
          updateData[field] = req.body[field];
        }
      }
      // 如果没有提交该字段，则保持原有值不变
    });
    
    const [updatedRowsCount] = await ChapterConfig.update(updateData, {
      where: { id }
    });
    
    if (updatedRowsCount === 0) {
      return res.status(404).json({
        success: false,
        message: '更新失败'
      });
    }
    
    const updatedConfig = await ChapterConfig.findByPk(id);
    
    res.json({
      success: true,
      message: '章节配置更新成功',
      data: updatedConfig
    });
  } catch (error) {
    console.error('更新章节配置失败:', error);
    res.status(500).json({
      success: false,
      message: '更新章节配置失败',
      error: error.message
    });
  }
};

// 删除章节配置（软删除）
const deleteChapterConfig = async (req, res) => {
  try {
    // 检查用户权限
    if (!req.user || !['admin', 'teacher'].includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足，只有管理员和教师可以删除章节配置'
      });
    }
    
    const { id } = req.params;
    
    const [updatedRowsCount] = await ChapterConfig.update(
      { 
        isActive: false,
        updatedBy: req.user.id
      },
      { where: { id } }
    );
    
    if (updatedRowsCount === 0) {
      return res.status(404).json({
        success: false,
        message: '章节配置不存在'
      });
    }
    
    res.json({
      success: true,
      message: '章节配置删除成功'
    });
  } catch (error) {
    console.error('删除章节配置失败:', error);
    res.status(500).json({
      success: false,
      message: '删除章节配置失败',
      error: error.message
    });
  }
};

module.exports = {
  getAllChapterConfigs,
  getChapterConfigByNumber,
  getMaxChapterNumber,
  createChapterConfig,
  updateChapterConfig,
  deleteChapterConfig
};